using System;
using System.Collections.Generic;

namespace IFXplus.SmartStorage.Providers
{
    internal static class StorageProviderFactory
    {
        private static readonly Dictionary<string, IStorageProvider> _StorageProviders = new Dictionary<string, IStorageProvider>();
        private static readonly object _syncRoot = new object();

        public static IStorageProvider GetStorageProvider(StorageProviderReference reference)
        {
            try
            {
                if (reference == null)
                   throw new ArgumentNullException("reference");
                if (string.IsNullOrEmpty(reference.Id))
                   throw new ArgumentException("reference.Id cannot be null or empty", "reference");
                
                if (!_StorageProviders.ContainsKey(reference.Id))
                {
                    lock(_syncRoot)
                    {
                        if (!_StorageProviders.ContainsKey(reference.Id))
                        {                            
                            switch (reference.Type)
                            {
                                
                                case StorageProviderType.AspNetCache:
                                    _StorageProviders.Add(reference.Id, new AspNetCacheStorageProvider(reference));
                                    break;

                                case StorageProviderType.Memory:
                                    _StorageProviders.Add(reference.Id, new MemoryStorageProvider(reference));
                                    break;

                                case StorageProviderType.FileSystem:
                                    _StorageProviders.Add(reference.Id, new FileSystemStorageProvider(reference));
                                    break;

                                case StorageProviderType.SqlServer:
                                    _StorageProviders.Add(reference.Id, new SqlServerStorageProvider(reference));
                                    break;

                                case StorageProviderType.WebService:
                                    _StorageProviders.Add(reference.Id, new WebServiceStorageProvider(reference));
                                    break;

                                default:
                                    throw new StorageException(string.Format("{0} provider not found", reference));
                            }
                        }
                    }
                }
                return _StorageProviders[reference.Id];
            }
            catch (Exception ex)
            {
                throw new StorageSettingsException("An error occurred retrieving the storage provider", ex);
            }
        }
    }
}
